package com.itlaobing.exam.handler;

import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.TypeHandler;

import java.sql.*;
import java.time.LocalDate;
import java.util.Objects;

public class LocalDateHandler implements TypeHandler<LocalDate> {

    @Override
    public void setParameter(PreparedStatement ps, int index, LocalDate localDate, JdbcType jdbcType) throws SQLException {
        java.sql.Date date = null;
        if (Objects.nonNull(localDate)){
            date = java.sql.Date.valueOf(localDate);
        }
        ps.setDate(index,date);
    }

    @Override
    public LocalDate getResult(ResultSet rs, String label) throws SQLException {
        LocalDate localDate = null;
        java.sql.Date date = rs.getDate(label);
        if (Objects.nonNull(date)){
            localDate = date.toLocalDate();
        }
        return localDate;
    }

    @Override
    public LocalDate getResult(ResultSet rs, int index) throws SQLException {
        LocalDate localDate = null;
        java.sql.Date date = rs.getDate(index);
        if (Objects.nonNull(date)){
            localDate = date.toLocalDate();
        }
        return localDate;
    }

    @Override
    public LocalDate getResult(CallableStatement cs, int index) throws SQLException {
        LocalDate localDate = null;
        java.sql.Date date = cs.getDate(index);
        if (Objects.nonNull(date)){
            localDate = date.toLocalDate();
        }
        return localDate;
    }
}
